package com.heima.file.service.impl;
import com.heima.file.common.enums.FileType;
import com.heima.file.service.FileService;
import com.heima.file.service.FileStorageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import java.util.UUID;

@Service
public class FileServiceImpl implements FileService {
    @Autowired
    FileStorageService ossService;
    @Autowired
    @Qualifier("minIOFileStorageService")
    FileStorageService minioService;
    @Value("${file.oss.web-site}")
    String webSite;
    @Value("${file.oss.prefix}")
    String ossPrefix;
    @Value("${file.minio.readPath}")
    String readPath;
    @Value("${file.minio.prefix}")
    String minioPrefix;
    @Override
    public String uploadFile(MultipartFile file, FileType fileType) throws Exception {
        // 1. 截取文件后缀
        String oldName = file.getOriginalFilename();
        String suffix = oldName.substring(oldName.lastIndexOf("."));
        // 2. 生成新文件名称
        String uuid = UUID.randomUUID().toString().replaceAll("-", "");
        // 3. 根据fileType决定是存储在oss中 还是 minio中
        String url = null;
        switch (fileType){
            case OSS:
                // 4. 返回上传成功的文件路径
                url = ossService.store(ossPrefix, uuid + suffix, file.getInputStream());
                return webSite + url;
            case MINIO:
                // 4. 返回上传成功的文件路径
                url = minioService.store(minioPrefix,oldName,"text/html",file.getInputStream());
                return readPath + url;
            default:
                throw new RuntimeException("暂不支持的存储类型");
        }
    }
    @Override
    public void deleteFile(String url, FileType fileType) {
        switch (fileType){
            case OSS:
                // 4. 返回上传成功的文件路径
                ossService.delete(url.replaceAll(webSite,""));
                break;
            case MINIO:
                // 4. 返回上传成功的文件路径
                minioService.delete(url);
                break;
            default:
                throw new RuntimeException("暂不支持的存储类型");
        }
    }
}
